package com.gsoe.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * [Sa-Token 权限认证] 配置类 
 * @author click33
 */
@Configuration
@Slf4j
public class SaTokenConfigure {
    // 注册 Sa-Token全局过滤器 
    @Bean
    public SaReactorFilter getSaReactorFilter() {
        return new SaReactorFilter()
            // 拦截地址 
            .addInclude("/**")    /* 拦截全部path */
            // 开放地址 
            .addExclude("/user/test/getUserInfo/**","/user/getCodeImage","/user/doRegister","/user/connect/**")
            .setAuth(obj -> {
                log.info("----- 请求path={}  提交token={}", SaHolder.getRequest().getRequestPath(), StpUtil.getTokenValue());
                SaRouter.match("/**", "/user/doLogin", r -> {StpUtil.checkLogin();});
                SaRouter.match(
                        "/judge/testCache/getTestCache/**",
                        "/judge/examCache/getExamCache/**",
                        "/judge/testCache/delByTextId/**",
                        "/judge/examCache/delByTextId/**"
                ).check(r->{throw new RuntimeException("禁止访问");});
            })
            // 异常处理方法：每次setAuth函数出现异常时进入 
            .setError(e -> {
                return SaResult.error(e.getMessage());
            })
            ;
    }
}
